//
//  LYXBingTuView.m
//  PosApp
//
//  Created by 刘萍 on 2018/9/14.
//  Copyright © 2018年 李英新. All rights reserved.
//

#import "LYXBingTuView.h"

#define COLOR_ARRAY @[\
[UIColor colorWithRed:242/255.0 green:164/255.0 blue:42/255.0 alpha:1],\
[UIColor colorWithRed:50/255.0 green:168/255.0 blue:235/255.0 alpha:1],\
[UIColor colorWithRed:246/255.0 green:179/255.0 blue:127/255.0 alpha:1],\
[UIColor colorWithRed:246/255.0 green:101/255.0 blue:52/255.0 alpha:1],\
[UIColor colorWithRed:41/255.0 green:201/255.0 blue:138/255.0 alpha:1],\
[UIColor colorWithRed:16/255.0 green:149/255.0 blue:224/255.0 alpha:1]\
]

#define CHART_MARGIN 0

@implementation LYXBingTuView

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}



- (void)draw {
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self setNeedsDisplay];
}


-(void)drawRect:(CGRect)rect{
    
    CGFloat min = self.bounds.size.width > self.bounds.size.height ? self.bounds.size.height : self.bounds.size.width;
    
    CGPoint center =  CGPointMake(self.bounds.size.width * 0.5, self.bounds.size.height * 0.5);
    CGFloat radius = min * 0.5 - CHART_MARGIN;
    CGFloat start = 0;
    CGFloat angle = 0;
    CGFloat end = start;
    
    if (self.dataArray.count == 0) {
        
        end = start + M_PI * 2;
//        UIColor *color = COLOR_ARRAY.firstObject;
        UIColor * color = [UIColor colorWithRed:arc4random_uniform(243)/255.0 green:arc4random_uniform(243)/255.0 blue:arc4random_uniform(243)/255.0 alpha:1.0];
        UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:start endAngle:end clockwise:true];
        
        [color set];
        //添加一根线到圆心
        [path addLineToPoint:center];
        [path fill];
        
    } else {
        for (int i = 0; i < self.dataArray.count; i++) {
            CGFloat percent = [self.dataArray[i] floatValue];
            UIColor *color = COLOR_ARRAY[i];
            start = end;
            angle = percent * M_PI * 2;
            end = start + angle;
            
            UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:start endAngle:end clockwise:true];
            [color set];
            //添加一根线到圆心
            [path addLineToPoint:center];
            [path fill];
        }
        
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
